// 2013-9-14下午01:08:37  net.betou.core.service.impl.ProxyListener.java

package net.betou.core.service.impl;

import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.Map.Entry;

import net.betou.core.entity.ConfigLogin;
import net.betou.core.service.AgencyOrProxyAbstract;
import net.betou.trade.entity.main.AgentAndAdmins;
import net.betou.trade.entity.main.Role;
import net.betou.trade.entity.main.RoleExt;
import net.betou.trade.main.manager.RoleExtMng;
import net.betou.trade.main.manager.role.AgencyRoleMng;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

/**
 * 
 * @author 叶装装
 */
public class ProxyListener extends AgencyOrProxyAbstract{

	public void afterSave( AgentAndAdmins bean ) {
		List< Role > roleList = getList( false );
		
		if( roleList == null || roleList.size( ) == 0 ){
			return;
		}
		String viewRoles = "";
		
		for( Role role : roleList ){
			// copy role... 
			role = copyRole( role, bean ); // 复制角色
			mng.save( role ); // 保存角色
			
			viewRoles += role.getId( ) + ",";
			
		}
		
		// 代理商角色
		initDefaultPermission( viewRoles, bean.getRoles( ).iterator( ).next( ) );
	}
	
	// 初始化代理商的附加权限
	private void initDefaultPermission( String viewRoles, Role proxyRole ){
		
		if( proxyRole == null || StringUtils.isBlank( viewRoles ) ){
			return;
		}
		
		viewRoles = viewRoles.substring( 0, viewRoles.length( ) - 1 ); // 去除最后一个逗号
		
	//	Set< RoleExt > roleSet = new HashSet< RoleExt >( );
		Set< Entry< String, String >> entrySet = ConfigLogin.roleExtMap.entrySet( );
		Iterator< Entry< String, String >> it = entrySet.iterator( );
		
		while( it.hasNext( ) ){
			
			Entry< String, String > entry = it.next( );
			RoleExt ext = new RoleExt( );

			ext.setKey( entry.getKey( ) );
			ext.setDescription( entry.getValue( ) );
			ext.init( );
			ext.setFindDeep( 10000 );
			ext.setViewRoles( viewRoles );
			
			ext = extMng.save( ext, proxyRole );
			//roleSet.add( ext );
		}

	}
	
	@Autowired
	private RoleExtMng extMng;
	
	@Autowired
	private AgencyRoleMng mng;

}
